package com.lyd.demo.api.v1;

import com.lyd.demo.api.dto.TestDto;
import com.lyd.demo.api.dto.ValidParamDto;
import com.lyd.demo.app.model.CustomServiceStatus;
import com.lyd.sweet.exception.SweetBasicException;
import com.lyd.sweet.model.ResponseObject;
import com.lyd.sweet.web.annotation.SweetResponseHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Api(tags = "DEMO测试API")
@RestController
@RequestMapping("/api/v1/test")
public class TestController {

    @ApiOperation("测试参数验证")
    @PostMapping("/test")
    public Boolean test(@Valid ValidParamDto dto) {
        return true;
    }

    @SweetResponseHandler
    @ApiOperation("测试响应无包装")
    @PostMapping("/test2")
    public Boolean test2(@Valid @RequestBody ValidParamDto dto) {
        return true;
    }

    @ApiOperation("测试服务自定义异常信息")
    @GetMapping("/test3")
    public Boolean test3() {
        throw new SweetBasicException("服务自定义异常信息");
    }

    @ApiOperation("测试服务自定义异常信息2")
    @GetMapping("/test33")
    public Boolean test33() {
        throw new SweetBasicException(new CustomServiceStatus("-1", "服务自定义异常信息及状态码"));
    }

    @ApiOperation("测试空指针异常提示")
    @GetMapping("/test4")
    public Boolean test4() {
        String name = null;
        return name.equals("木木");
    }

    @ApiOperation("测试IO异常提示")
    @GetMapping("/io/error")
    public Boolean test5() throws IOException {
        Files.readAllBytes(Paths.get("/none/none.txt"));
        return true;
    }

    @ApiOperation("测试PUT-Method")
    @PutMapping
    public Boolean test6(@Valid @RequestBody ValidParamDto dto) {
        return true;
    }

    @ApiOperation("测试Delete-Method")
    @DeleteMapping("/{id}")
    public Boolean test7(@PathVariable Long id) {
        return true;
    }

    @ApiOperation("测试swagger文件上传")
    @PostMapping
    public String test8(MultipartFile file) {
        return file.getName();
    }

    @ApiOperation("测试swagger文件上传2")
    @PostMapping("/upload")
    public String test9(TestDto dto) {
        return dto.getFile().getName();
    }

    @ApiOperation("测试结果封装")
    @PostMapping("/upload2")
    public ResponseObject<String> test10(TestDto dto) {
        try {
            return ResponseObject.success(dto.getFile().getOriginalFilename());
        } catch (Exception e){
            return ResponseObject.fail(e.getMessage());
        }
    }

}
